package com.sukumar.android.backit.activity;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.sukumar.android.backit.R;
import com.sukumar.android.backit.bean.BackItRuleBean;
import com.sukumar.android.backit.db.BackItDBData.BackItRule;

public class BackItRuleListActivity extends Activity {
	ListView list;
	ArrayList<BackItRuleBean> arrRuleList = new ArrayList<BackItRuleBean>();
	ArrayList<BackItRuleBean> selRuleList = new ArrayList<BackItRuleBean>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rule_list_layout);
		getRulesFromDB();
		list = (ListView) findViewById(R.id.myrule_list);
		ArrayAdapter<BackItRuleBean> adapter = new ArrayAdapter<BackItRuleBean>(
				this, R.layout.bing_list, arrRuleList);
		list.setAdapter(adapter);
		list.setItemsCanFocus(false);
		list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		if (arrRuleList.size() == 1 && arrRuleList.get(0).getRuleId() == -9999) {
			list.setClickable(false);
			list.setLongClickable(false);
			unregisterForContextMenu(list);
		} else {
			registerForContextMenu(list);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.rule_list_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getTitle().equals("Add rule")) {
			startActivity(new Intent(getApplicationContext(),
					BackItRulePreferenceActivity.class));
		} else if (item.getTitle().equals("Refresh list")) {
			refreshListView();
		} else if (item.getTitle().equals("Delete all")) {
			deleteAllRules();
			refreshListView();
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.myrule_list) {
			int selCount = addItemsToSelection();
			if (selCount > 0) {
				menu.setHeaderTitle(R.string.long_click_action);
				String[] menuItems = getResources().getStringArray(
						R.array.rule_context_menu);
				for (int i = (menuItems.length/2+1); i < menuItems.length; i++) {
					menu.add(Menu.NONE, i, i, menuItems[i]);
				}
			}else{
				menu.setHeaderTitle(R.string.long_click_action);
				String[] menuItems = getResources().getStringArray(
						R.array.rule_context_menu);
				for (int i = 0; i < (menuItems.length/2+1); i++) {
					menu.add(Menu.NONE, i, i, menuItems[i]);
				}
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		BackItRuleBean selRule = arrRuleList.get(info.position);
		switch (menuItemIndex) {
		case 0:
			editRule(selRule);
			break;
		case 1:
			deleteRule(selRule);
			refreshListView();
			Toast.makeText(getApplicationContext(), "Rule deleted.",
					Toast.LENGTH_SHORT).show();
			break;
		case 2:
			addItemsToSelection();
			deleteSelectedRules();
			refreshListView();
			break;

		}
		return super.onContextItemSelected(item);
	}

	private void editRule(BackItRuleBean selRule) {
		Intent editIntent = new Intent(getApplicationContext(),
				BackItRulePreferenceActivity.class);
		SharedPreferences sharedpref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		Editor spEdi = sharedpref.edit();
		spEdi.putString(getText(R.string.rule_name_key).toString(),
				selRule.getRuleName());
		spEdi.putString(getText(R.string.pattern_key).toString(),
				selRule.getPattern());
		spEdi.putString(getText(R.string.rule_rt_key).toString(),
				selRule.getNotificationUri());
		spEdi.putBoolean(getText(R.string.vibration_key).toString(),
				selRule.isVibrate());
		spEdi.putBoolean(getText(R.string.rule_enabled_key).toString(),
				selRule.isRuleEnabled());
		spEdi.putString(getText(R.string.rule_repeat_key).toString(),
				getTime(selRule.getRepeat()));

		spEdi.commit();
		startActivity(editIntent);
	}

	private int deleteRule(BackItRuleBean selRule) {
		int delCount = 0;
		boolean flag = selRule.getPattern().equals("BING");
		if (!flag) {
			String strWhere = BackItRule._ID + " = ?";
			delCount = getContentResolver().delete(BackItRule.CONTENT_URI,
					strWhere, new String[] { selRule.getRuleId() + "" });
		}
		return delCount;
	}

	private int deleteAllRules() {
		int delCount = 0;
		BackItRuleBean ruleBean = null;
		for (Iterator<BackItRuleBean> iterator = arrRuleList.iterator(); iterator
				.hasNext();) {
			ruleBean = iterator.next();
			delCount += deleteRule(ruleBean);
		}
		return delCount;
	}

	private int deleteSelectedRules() {
		int delCount = 0;
		BackItRuleBean ruleBean = null;
		for (Iterator<BackItRuleBean> iterator = selRuleList.iterator(); iterator
				.hasNext();) {
			ruleBean = iterator.next();
			delCount += deleteRule(ruleBean);
		}
		return delCount;
	}

	private void getRulesFromDB() {
		Cursor c = getContentResolver().query(
				BackItRule.CONTENT_URI,
				new String[] { BackItRule._ID, BackItRule.RULENAME,
						BackItRule.PATTERN, BackItRule.NOTIFURI,
						BackItRule.VIBRATE, BackItRule.ENABLED,
						BackItRule.REPEAT }, null, null, null);
		BackItRuleBean smsRuleBean = null;
		try {
			if (c != null && c.getCount() > 0) {
				c.moveToFirst();
				do {
					smsRuleBean = new BackItRuleBean();
					smsRuleBean.setRuleId(c.getInt(0));
					smsRuleBean.setRuleName(c.getString(1));
					smsRuleBean.setPattern(c.getString(2));
					smsRuleBean.setNotificationUri(c.getString(3));
					smsRuleBean.setVibrate((c.getString(4).equals("Y") ? true
							: false));
					smsRuleBean
							.setRuleEnabled((c.getString(5).equals("Y") ? true
									: false));
					smsRuleBean.setRepeat(c.getInt(6));
					arrRuleList.add(smsRuleBean);
				} while (c.moveToNext());
			}
		} catch (Exception e) {

		} finally {
			c.close();
		}

	}

	private void refreshListView() {
		arrRuleList.clear();
		getRulesFromDB();
		list.setAdapter(new ArrayAdapter<BackItRuleBean>(this,
				R.layout.bing_list, arrRuleList));
		if (arrRuleList.size() == 1 && arrRuleList.get(0).getRuleId() == -9999) {
			list.setClickable(false);
			list.setLongClickable(false);
			unregisterForContextMenu(list);
		} else {
			registerForContextMenu(list);
		}
	}

	private int addItemsToSelection() {
		int count = this.list.getAdapter().getCount();
		int selCount = 0;
		selRuleList.clear();
		for (int i = 0; i < count; i++) {
			if (this.list.isItemChecked(i)) {
				Object data = this.list.getItemAtPosition(i);
				selRuleList.add((BackItRuleBean) data);
				selCount++;
			}
		}
		return selCount;
	}

	private String getTime(int duration) {
		String strTime = "mm:ss";
		if (duration != -99) {
			int min = duration / 60;
			int sec = duration % 60;
			strTime = min + ":" + sec;
		}
		return strTime;
	}
}
